package net.oktaeder.office.utils.generators;

import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Class used to generate personal identification numbers for people
 * 
 * @author tuukka
 *
 */
public class PINGenerator {

	private static Log log = LogFactory.getLog(PINGenerator.class);
	private static PINGenerator instance;
	private Hashtable<Date, Integer> count;
	
	private PINGenerator() {
		count = new Hashtable<Date, Integer>();
	}
	
	public static synchronized PINGenerator getInstance() {
		try {
			if (instance == null) {
				instance = new PINGenerator();
			}
			return instance;
		} catch (Exception ex) {
			log.error("failed to get instance of the PIN Generator", ex);
			return null;
		}
	}
	
	public String getPIN(Date birthDay) throws Exception {
		String ending;
		String beginning;
		Calendar calendar;
		Integer value;
		int day;
		int month;
		int year;
		
		String dayString;
		String monthString;
		String yearString;
		
		try {
			calendar = Calendar.getInstance();
			calendar.setTime(birthDay);
			
			if (count.containsKey(birthDay)) {
				value = count.get(birthDay);
				value = value + 1;
				ending = value.toString();
				count.remove(birthDay);
				count.put(birthDay, value);
			} else {
				ending = "1";
				count.put(birthDay, new Integer(1));
			}
			
			day = calendar.get(Calendar.DAY_OF_MONTH);
			month = calendar.get(Calendar.MONTH);
			year = calendar.get(Calendar.YEAR);
			
			if (day < 10) {
				dayString = "0" + String.valueOf(day);
			} else {
				dayString = String.valueOf(day);
			}
			
			if (month < 10) {
				monthString = "0" + String.valueOf(month);
			} else {
				monthString = String.valueOf(month);
			}
			
			yearString = String.valueOf(year);
			
			beginning = dayString + monthString + yearString;
			
			return beginning + "-" + ending;			
		} catch (Exception ex) {
			log.error("failed to generate PIN", ex);
			throw new Exception("failed to generate PIN", ex);
		}
	}
}